#!/usr/bin/env python
#coding=gbk
from mutagen.easyid3 import EasyID3
from mutagen.mp3 import MP3
from mutagen.id3 import TCON
import sys
import mutagen

def MakeID3v1(id3, enc):
    """Return an ID3v1.1 tag string from a dict of ID3v2.4 frames."""

    """Copied from id3.py of mutagen. What I modified is the encoding of ID3v1, so that the tag can be parsed
    correctly by Windows Media Player, etc."""

    v1 = {}

    for v2id, name in {"TIT2": "title", "TPE1": "artist",
                       "TALB": "album"}.items():
        if v2id in id3:
            text = id3[v2id].text[0].encode(enc, 'replace')[:30]
        else:
            text = ""
        v1[name] = text + ("\x00" * (30 - len(text)))

    if "COMM" in id3:
        cmnt = id3["COMM"].text[0].encode(enc, 'replace')[:28]
    else: cmnt = ""
    v1["comment"] = cmnt + ("\x00" * (29 - len(cmnt)))

    if "TRCK" in id3:
        try: v1["track"] = chr(+id3["TRCK"])
        except ValueError: v1["track"] = "\x00"
    else: v1["track"] = "\x00"

    if "TCON" in id3:
        try: genre = id3["TCON"].genres[0]
        except IndexError: pass
        else:
            if genre in TCON.GENRES:
                v1["genre"] = chr(TCON.GENRES.index(genre))
    if "genre" not in v1: v1["genre"] = "\xff"

    if "TDRC" in id3:
        v1["year"] = str(id3["TDRC"])[:4]
    elif "TYER" in id3:
        v1["year"] = str(id3["TYER"])[:4]
    else:
        v1["year"] = "\x00\x00\x00\x00"

    return ("TAG%(title)s%(artist)s%(album)s%(year)s%(comment)s"
            "%(track)s%(genre)s") % v1

def saveTagToFile(filename, fileID3, v1enc):
    """ Update the file."""
    #fileID3.save(v1=1)

    try:
        hasID3v1 = has_id3v1(filename)
        try: f = open(filename, 'rb+')
        except IOError, err:
            from errno import ENOENT
            if err.errno != ENOENT: raise
            f = open(filename, 'ab') # create, then reopen
            f = open(filename, 'rb+')

        v1 = 2
        if hasID3v1:
            f.seek(-128, 2)
            if v1 > 0: f.write(MakeID3v1(fileID3, v1enc))
            else: f.truncate()
        elif v1 == 2:
            f.seek(0, 2)
            f.write(MakeID3v1(fileID3, v1enc))
    finally:
        f.close()


def id3v2_to_id3v1(name,enc):
    saveTagToFile(name,mutagen.id3.ID3(name),enc)
